package com.gitee.mars.tourserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mars.tourserver.exception.WorkException;
import com.gitee.mars.tourserver.request.HotelOrderRequest;
import com.gitee.mars.tourserver.response.base.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gitee.mars.tourserver.service.IHotelOrderService;
import com.gitee.mars.tourserver.mapper.HotelOrderMapper;
import com.gitee.mars.tourserver.entity.HotelOrder;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;


/**
 * HotelOrder 实现层
 *
 * @Author wq
 * @Date 2021-05-10
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class HotelOrderServiceImpl extends ServiceImpl<HotelOrderMapper, HotelOrder> implements IHotelOrderService {


    @Override
    public void createOrder(HotelOrderRequest request) {
        HotelOrder hotelOrder = new HotelOrder();
        HotelOrder hotelOrder1 = baseMapper.selectOne(new LambdaQueryWrapper<HotelOrder>().eq(HotelOrder::getHotelId, request.getHotelId()).eq(HotelOrder::getUserId, request.getUserId()));
        if (Objects.nonNull(hotelOrder1)) {
            throw new WorkException("你已经下过单了");
        }
        hotelOrder.setHotelId(request.getHotelId());
        hotelOrder.setUserId(request.getUserId());
        hotelOrder.setCreateTime(new Date());
        hotelOrder.setOrderId(getOrderIdByTime());
        hotelOrder.setUpdateTime(new Date());
        save(hotelOrder);

    }

    @Override
    public PageInfo<HotelOrder> list(HotelOrderRequest request) {
        IPage<HotelOrder> page = new Page<>(request.getPageNumber(), request.getPageSize());
        LambdaQueryWrapper<HotelOrder> wrapper = new LambdaQueryWrapper<>();
        IPage<HotelOrder> hotelOrderIPage = baseMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(hotelOrderIPage.getRecords())) {
            return new PageInfo<>(page.getTotal(), hotelOrderIPage.getRecords());
        }
        return null;
    }


    public static String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result.append(random.nextInt(10));
        }
        return newDate + result;
    }
}